package com.csi.service.impl;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.csi.domain.*;
import com.csi.mapper.HotelMapper;
import com.csi.service.HotelService;
import com.csi.utils.MD5Utils;
import com.csi.utils.OssUtil;
import com.csi.utils.ReturnResults;
import com.csi.utils.SMS;
import org.apache.commons.lang3.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class HotelServiceImpl implements HotelService {

    @Autowired
    private HotelMapper hotelMapper;

    /**
     * 热门酒店推荐
     * @return
     */
    @Override
    public List<Hotel> hotHotel() {
        return hotelMapper.hotHotel();
    }

    /**
     * 查找全部酒店
     * @return
     */
    @Override
    public List<Hotel> findAll() {
        return hotelMapper.findAll();
    }

    /**
     * 酒店首页多条件查询
     * @param peopleNum
     * @param cityLocation
     * @param checkTime
     * @param leaveTime
     * @return
     */
    @Override
    public List<Hotel> like4book(Integer peopleNum, String cityLocation, String checkTime, String leaveTime) {
        return hotelMapper.like4book(peopleNum, cityLocation, checkTime, leaveTime);
    }

    /**
     * 酒店详情
     * @param hotelId
     * @return
     */
    @Override
    public Map<String, Object> findHotelListById(long hotelId) {
        Map<String,Object> hotelBase =  hotelMapper.findHotelListById(hotelId);

        if (hotelBase != null){
            List<FacilityInfo> hotelFacilities = hotelMapper.findHotelFacilities(hotelId);
            hotelBase.put("facilities",hotelFacilities);
        }
        return hotelBase;
    }
    /**
     * 查询房间类型
     * @param hotelId 酒店id
     * @param checkTime 入住时间
     * @param leaveTime 离店时间
     * @return Map<String,Object>
     */
    @Override
    public List<Map<String, Object>> findRoomTypeById(long hotelId, String checkTime, String leaveTime) {

        List<Map<String, Object>> roomType = hotelMapper.findRoomTypeById(hotelId,checkTime,leaveTime);

        for (Map<String, Object> m :roomType){
            List<FacilityInfo> roomFacilitiesById = hotelMapper.findRoomFacilitiesById((Long) m.get("id"));
            m.put("facilities",roomFacilitiesById);
        }
        return roomType;
    }

    /**
     * 酒店入驻
     * @param hotel
     * @param multipartFiles
     * @return
     */
    @Override
    @Transactional
    public int save(Hotel hotel, MultipartFile[] multipartFiles) {
        List<String> filesHrefs = new ArrayList<>();
        if (multipartFiles!=null && multipartFiles.length>0){
            // 遍历文件列表，逐个上传
            for (MultipartFile uploadFile : multipartFiles) {
                // 调用 OssUtil 上传文件
                try {
                    filesHrefs.add(OssUtil.upload(uploadFile.getOriginalFilename(), uploadFile.getInputStream(), "hotelImage"));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        }
        StrBuilder bu = new StrBuilder();
        if (filesHrefs.size() > 1){
            for (int i = 0; i < filesHrefs.size(); i++) {
                bu.append(filesHrefs.get(i));
                if (i < filesHrefs.size() - 1) { // 最后一个文件不加分号
                    bu.append(";");
                }
            }
        }else {
            bu.append(filesHrefs.get(0));
        }
        hotel.setHotelImg(bu.toString());
        int saved =  hotelMapper.save(hotel);

        Role role = new Role();
        role.setHotelId(hotel.getId());
        hotelMapper.insertRole(role);

        Employee employee = new Employee();
        employee.setHotelId(hotel.getId());
        //发送的用户名
        String username = PinyinUtil.getPinyin(hotel.getHotelContext()).replace(" ","");
        //发送的密码
        String password = String.valueOf(ThreadLocalRandom.current().nextInt(100000, 1000000)); // 100000 到 999999 之间
        //发送用户名密码，短信
        System.out.println(hotel.getHotelPhone()+"=================================");
        try {
            SMS.userInfo(hotel.getHotelPhone(),username,password);
        } catch (Exception e) {
            return 0;
        }

        employee.setUsername(username);
        employee.setPassword(MD5Utils.getMD5String(password));
        employee.setEntryTime(new Timestamp(System.currentTimeMillis()));
        employee.setCreateId(0);
        employee.setRoleId(role.getId());
        employee.setName(hotel.getHotelContext());
        employee.setHotelId(hotel.getId());
        hotelMapper.generateEmployee(employee);

        hotel.getHotelLocation().setHotelId(hotel.getId());
        hotel.getHotelLocation().setDetailLocation(hotel.getHotelAddress());
        int saveLocation =  hotelMapper.saveLocation(hotel.getHotelLocation());
        int audited = hotelMapper.saveHotelAudit(hotel.getId(), ReturnResults.WAIT_AUDIT_STATUS);
        return saveLocation + audited + saved;
    }

    @Override
    public List<Hotel> findHotelByCity(String cityName) {
        return hotelMapper.findHotelByCity(cityName);
    }

    /**
     * 根据酒店id查询房型
     * @param hotelId 酒店id
     * @return 请求结果
     */
    @Override
    public List<RoomType> findAllRoomType(long hotelId) {
        return hotelMapper.findAllRoomType(hotelId);
    }

    @Override
    public List<Map<String, Object>> findHotelByUserId(long userId) {
        return hotelMapper.findHotelByUserId(userId);
    }

    @Override
    public List<Map<String, Object>> findBillByLike(long userId, String status) {
        return hotelMapper.findBillByLike(userId,status);
    }

    @Override
    public String findHotelName(long hotelId) {
        return hotelMapper.findHotelNameById(hotelId);
    }

    @Override
    public List<Hotel> discountedhotel() {
        return hotelMapper.discountedhotel();
    }


}
